<template>
  <el-form
    ref="ruleFormRef"
    style="max-width: 600px"
    :model="ruleForm"
    :rules="rules"
    label-width="auto"
  >
    <el-form-item label="商品名称" prop="Goods_Name">
      <el-input v-model="ruleForm.Goods_Name" />
    </el-form-item>

    <el-form-item label="商品品牌">
      <el-select v-model="ruleForm.GoodsBrand_Id" placeholder="请选择商品品牌">
        <el-option v-for="item in goodsBrandInfo" :label="item.goodsBrand_Name" :value="item.goodsBrand_Id" />
      </el-select>
    </el-form-item>

    <el-form-item label="商品分类">
     <el-cascader
      v-model="ruleForm.GoodsType_Array"
      :options="options"
      :props="props"
      @change="handleChange"
    />
    </el-form-item>

     <el-form-item label="商品价格" prop="Goods_Price">
      <el-input v-model="ruleForm.Goods_Price" />
    </el-form-item>

    <el-form-item label="商品预览图" required>
      <el-upload
        class="avatar-uploader"
        action="http://localhost:42025/api/Imgs/Img"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload"
      >
        <img v-if="ruleForm.Goods_Img" :src="ruleForm.Goods_Img" class="avatar" />
        <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
      </el-upload>
    </el-form-item>

     <el-form-item label="状态">
      <el-radio-group v-model="ruleForm.Goods_State">
        <el-radio :value="true">上架</el-radio>
        <el-radio :value="false">下架</el-radio>
      </el-radio-group>
    </el-form-item>

    <el-form-item label="商品描述" prop="delivery">
      <div style="border: 1px solid #ccc">
     <Toolbar
        style="border-bottom: 1px solid #ccc"
        :editor="editorRef"
        :defaultConfig="toolbarConfig"
        :mode="mode"
      />
      <Editor
        style="height: 500px; overflow-y: hidden;"
        v-model="ruleForm.Goods_Remark"
        :defaultConfig="editorConfig"
        :mode="mode"
        @onCreated="handleCreated"
      />
      </div>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="submitForm(ruleFormRef)">
        保存
      </el-button>
      <el-button @click="resetForm(ruleFormRef)">重置</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import type { FormInstance, FormRules,UploadProps } from 'element-plus'
import axios from 'axios'
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { onBeforeUnmount, ref, shallowRef, onMounted,reactive } from 'vue'
import { Editor, Toolbar } from '../../../node_modules/@wangeditor/editor-for-vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'


const ruleFormRef = ref<FormInstance>()

//表单数据(响应式数据)
const ruleForm = reactive({
  Goods_Name: '',
  Goods_Price: '',
  Goods_Img: '',
  Goods_State: '',
  Goods_Remark: '',
  GoodsBrand_Id: '',
  GoodsType_Id: '',
  GoodsType_Array:[]
})

//声明响应式数据接受商品品牌信息
const goodsBrandInfo=ref([{
    goodsBrand_Id:0,
    goodsBrand_Name:''
}]);

//组件的验证规则
const rules = reactive<FormRules>({
  Goods_Name: [
    { required: true, message: '商品名称不能为空', trigger: 'blur' },
    { min: 2, max: 6, message: '商品名称需介于2-6位', trigger: 'blur' },
    { pattern:/^[\u4e00-\u9fa5]{2,6}/,message:'商品名称需为中文',trigger:'blur'}  //加入正则表达式验证
  ],
   Goods_Price: [
    { required: true, message: '商品价格不能为空', trigger: 'blur' }
  ],
})

//表单提交事件
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      //将商品分类的数组转换为字符串
      ruleForm.GoodsType_Id=ruleForm.GoodsType_Array.toString();
    

      //输出表单数据
    axios.post("/api/Goods/AddGoods",ruleForm)
    .then(res=>{
      if(res.data.data>0)
      {
        ElMessage.success("商品添加成功");
      }
      else if(res.data.data==-1)
      {
        ElMessage.warning("商品名称重复，请更换！");
      }
      else{
         ElMessage.error("商品添加失败");
      }
    })
    } else {
      console.log('error submit!', fields)
    }
  })
}

//表单重置事件
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

//声明生命周期函数，加载钩子
onMounted(()=>{
  //完成商品品牌信息加载
  LoadGoodsBrand();

//完成商品分类信息加载
  LoadGoodsType();
})

//完成商品品牌信息加载
const LoadGoodsBrand=()=>{
    axios.get("/api/Goods/ShowGoodsBrand")
    .then(res=>{
        goodsBrandInfo.value=res.data.data;
    })
}

//完成商品分类信息加载
const LoadGoodsType=()=>{
  axios.get('http://localhost:42025/api/Goods/ShowGoodsType?parentid=0')
  .then(res=>{
    options.value=res.data.data;
  })

}


//声明参数
  const mode=ref();

   // 编辑器实例，必须用 shallowRef
      const editorRef = shallowRef()


      const toolbarConfig = {}
      const editorConfig = { placeholder: '请输入内容...' }

      // 组件销毁时，也及时销毁编辑器
      onBeforeUnmount(() => {
        const editor = editorRef.value
        if (editor == null) return
        editor.destroy()
      })

      const handleCreated = (editor:any) => {
        editorRef.value = editor // 记录 editor 实例，重要！
      }



const props = {
  expandTrigger: 'hover' as const,
}

const handleChange = (value:any) => {
  console.log(value)
}

//label：显示数据名称  value:绑定显示名称的唯一标识(id\主键)
const options = ref([]);




//文件上传后的回调
const handleAvatarSuccess = (imgUrl:any) => {
  ruleForm.Goods_Img=imgUrl;
}

//图片上传前的验证
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('上传文件的格式必须为JPG!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('文件上传大小不得大于2MB!')
    return false
  }
  return true
}

</script>



<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>